﻿using System;
using System.Text;
using System.Runtime.InteropServices;
using System.Drawing;

namespace Win32
{
	public static class ExternWindow
	{
		[DllImport("User32.dll")]
		static extern IntPtr GetForegroundWindow();

		[DllImport("User32.dll")]
		static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);

		[StructLayout(LayoutKind.Sequential)]
		public struct RECT
		{
			public int left;
			public int top;
			public int right;
			public int bottom;
		}

		[DllImport("User32.dll")]
		static extern int GetWindowRect(IntPtr hWnd, ref RECT rect);

		public static string GetActiveWindowTitle()
		{
			const int maxChars = 256;
			IntPtr hWnd = IntPtr.Zero;
			StringBuilder buffer = new StringBuilder(maxChars);
			hWnd = GetForegroundWindow();

			if(hWnd != IntPtr.Zero)
			{
				if (GetWindowText(hWnd, buffer, maxChars) > 0)
				{
					return buffer.ToString();
				}
			}

			return String.Empty;
		}

		public static Rectangle GetActiveWindowRect()
		{
			IntPtr hWnd = IntPtr.Zero;
			hWnd = GetForegroundWindow();
			RECT r = new RECT();

			if (hWnd != IntPtr.Zero)
			{
				if (GetWindowRect(hWnd, ref r) > 0)
				{
					Rectangle rect = new Rectangle(r.left, r.top, r.right - r.left, r.bottom - r.top);
					return rect;
				}
			}

			return new Rectangle();
		}
	}
}
